/**
 * 全局认证守卫组件
 * 在应用级别检查用户登录状态
 */

import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Spin } from 'antd';
import { isPublicRoute, saveRedirectPath, AUTH_STORAGE_KEYS } from '../config/authConfig';
import { showAuthModal } from './AuthModal';

interface AuthGuardProps {
  children: React.ReactNode;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const [isChecking, setIsChecking] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    checkAuth();
  }, [location.pathname]);

  // 检查认证状态
  const checkAuth = () => {
    const currentPath = location.pathname;
    
    // 如果是公开路由，直接放行
    if (window.Location.hostname === 'localhost' || isPublicRoute(currentPath)) {
      setIsAuthenticated(true);
      setIsChecking(false);
      return;
    }

    // 检查token
    const token = localStorage.getItem(AUTH_STORAGE_KEYS.TOKEN);
    const userInfo = localStorage.getItem(AUTH_STORAGE_KEYS.USER);

    if (!token || !userInfo) {
      // 未登录状态
      handleUnauthenticated();
    } else {
      // 已登录
      setIsAuthenticated(true);
      setIsChecking(false);
    }
  };

  // 处理未认证的情况
  const handleUnauthenticated = () => {
    setIsChecking(false);
    setIsAuthenticated(false);

    // 保存当前路径
    const fullPath = location.pathname + location.search;
    saveRedirectPath(fullPath);

    // 如果是根路径，直接跳转到登录页
    if (location.pathname === '/' || location.pathname === '') {
      navigate('/login', { replace: true });
      return;
    }

    // 显示认证提示Modal
    showAuthModal({
      onLogin: () => {
        navigate('/login');
      },
      onClose: () => {
        // 用户选择稍后再说，跳转到首页
        navigate('/', { replace: true });
      }
    });
  };

  // 监听localStorage变化（多标签页同步）
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === AUTH_STORAGE_KEYS.TOKEN) {
        if (!e.newValue && !isPublicRoute(location.pathname)) {
          // Token被移除，需要重新认证
          handleUnauthenticated();
        } else if (e.newValue && !isAuthenticated) {
          // Token被添加，刷新页面
          window.location.reload();
        }
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [location.pathname, isAuthenticated]);

  // 加载中状态
  if (isChecking) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        background: '#f0f2f5'
      }}>
        <Spin size="large" tip="验证登录状态...">
          <div style={{ height: '200px', width: '200px' }} />
        </Spin>
      </div>
    );
  }

  return <>{children}</>;
};

export default AuthGuard;